package com.frame.auth.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @auther zhangwj
 * @date 2021/3/11 上午10:25
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final static String[] AUTHENTICATED_URL = {"/**"};

    private final static String LOGIN_PAGE = "/login/index";

    private final static String LOGIN_PROCESS_URL = "/login";

    private final static String OAUTH_AUTHORIZE = "/oauth/**";

    private final static String[] AUTHORIZE_REQUESTS_URL = {"/oauth/**", "/login/**", "/access/**"};

    private final static String[] REQUEST_MATCHERS_URL = {LOGIN_PAGE, LOGIN_PROCESS_URL, OAUTH_AUTHORIZE};

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.httpBasic();
        // 必须配置，不然OAuth2的http配置不生效----不明觉厉
        http.requestMatchers().antMatchers(REQUEST_MATCHERS_URL);
        http.authorizeRequests().antMatchers(AUTHORIZE_REQUESTS_URL).permitAll()
                .antMatchers(AUTHENTICATED_URL).authenticated().anyRequest().permitAll();
        http.formLogin().loginPage(LOGIN_PAGE).loginProcessingUrl(LOGIN_PROCESS_URL);

        http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);
        http.sessionManagement().sessionFixation().none();
    }
}
